package com.study.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionBindingEvent;

@WebListener
public class OnlineListener implements ServletContextListener,
        HttpSessionListener, HttpSessionAttributeListener {

    private static int onlineCount=0;
    private static int loginCount=0;
    public OnlineListener() {
    }
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("OnlineListener的contextInitialized.....");
        sce.getServletContext().setAttribute("onlineCount",onlineCount);
        sce.getServletContext().setAttribute("loginCount",loginCount);
    }
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("OnlineListener的contextDestroyed.....");
    }

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("OnlineListener的sessionCreated.....");
        onlineCount++;
        se.getSession().getServletContext().setAttribute("onlineCount",onlineCount);
        System.out.println(se.getSession().getId()+"在线人数为:"+onlineCount);
    }
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("OnlineListener的sessionDestroyed.....");
        onlineCount--;
        se.getSession().getServletContext().setAttribute("onlineCount",onlineCount);
        System.out.println("在线人数为:"+onlineCount);
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent sbe) {
        if(sbe.getName().equals("user")){
            loginCount++;
            sbe.getSession().getServletContext().setAttribute("loginCount",loginCount);
            System.out.println("在线人数为:"+onlineCount);

        }
        System.out.println("OnlineListener的attributeAdded.....");
    }
    @Override
    public void attributeRemoved(HttpSessionBindingEvent sbe) {
        if(sbe.getName().equals("user")){
            loginCount--;
            sbe.getSession().getServletContext().setAttribute("loginCount",loginCount);
            System.out.println("在线人数为:"+onlineCount);
        }
        System.out.println("OnlineListener的sessionDestroyed.....");
    }
    @Override
    public void attributeReplaced(HttpSessionBindingEvent sbe) {
        System.out.println("OnlineListener的sessionDestroyed.....");
    }
}
